package com.gitee.tanmingjian.httptunnel.handler;


import com.gitee.tanmingjian.httptunnel.core.HttpTunnelService;
import com.gitee.tanmingjian.httptunnel.core.bean.QueryParam;
import org.springframework.http.MediaType;
import org.springframework.util.MultiValueMap;
import org.springframework.web.servlet.function.ServerRequest;
import org.springframework.web.servlet.function.ServerResponse;

import java.io.IOException;
import java.util.Map;

public class HttpTunnelHandler {

    private final HttpTunnelService httpTunnelService;
    private final String basePath;

    public HttpTunnelHandler(String basePath, HttpTunnelService httpTunnelService) {
        this.basePath = basePath;
        this.httpTunnelService = httpTunnelService;
    }

    public ServerResponse index(ServerRequest request) throws IOException {
        String contextPath = request.servletRequest().getContextPath().concat(basePath);
        return ServerResponse.ok().contentType(MediaType.TEXT_HTML).body(httpTunnelService.getIndexHtml(contextPath));
    }

    public ServerResponse post(ServerRequest request) {
        MultiValueMap<String, String> params = request.params();
        QueryParam queryParam = new QueryParam();
        queryParam.setHost(params.getFirst("host"));
        queryParam.setPort(params.getFirst("port"));
        queryParam.setLogin(params.getFirst("login"));
        queryParam.setPassword(params.getFirst("password"));
        queryParam.setDb(params.getFirst("db"));
        queryParam.setActn(params.getFirst("actn"));
        queryParam.setEncodeBase64(params.getFirst("encodeBase64"));
        queryParam.setQ(params.get("q[]"));

        Map<String, String> pathVariables = request.pathVariables();
        String sessionId = pathVariables.getOrDefault("sessionId", "default");

        return ServerResponse.ok().contentType(MediaType.APPLICATION_OCTET_STREAM).body(httpTunnelService.process(queryParam, sessionId));
    }

}
